import {
  ModalForm,
  ProCard,
  ProFormInstance,
  ProFormText,
  ProFormUploadDragger,
} from '@ant-design/pro-components';
import { Button, message, Upload } from 'antd';
import type { UploadProps } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import {
  DownloadOutlined,
  UploadOutlined,
  FileSearchOutlined,
  InboxOutlined,
} from '@ant-design/icons';
import { useRequest } from 'umi';
import { TemplateUrlAdapter } from './Adapter';
import TbaleExplainMap from '@/components/TipsMap';

const { Dragger } = Upload;

/**
 * 模块主页面中用于上传和下载Excel模板 函数
 * @param tableName 表名称
 * @param url 用于刷新当前表单
 * @param dataForm 刷新表单需要的参数
 * @returns 组件数组
 */
export const UpLoadTemplate = (tableName: any, url: String, dataForm: any) => {
  const MyExtra = [];
  const formRef = useRef<ProFormInstance>();
  const findInfoByDataForm = useRequest((data = {}) => {
    return {
      url: url,
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });
  const uploadExcel = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/import/importData`, //?file=${data}&${data?.tableName}
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        body: data,
      };
    },
    {
      manual: true,
    },
  );

  if (localStorage.getItem('identity') === '管理员') {
    console.log(localStorage.getItem('identity'));

    MyExtra.push(
      <ModalForm
        title="可批量导入表格文件"
        trigger={
          <Button type="primary">
            <UploadOutlined />
            导入文件
          </Button>
        }
        formRef={formRef}
        autoFocusFirstInput
        submitTimeout={2000}
        onFinish={async (values) => {
          console.log(values);
          var formData = new FormData();
          formData.append('file', values.file[0].originFileObj);
          formData.append('tableName', tableName);
          uploadExcel.run(formData).then((e) => {
            message.success('上传成功');
            findInfoByDataForm.run(dataForm);
          });
          return true;
        }}
        key="1"
      >
        <ProFormUploadDragger
          // label="可上传多个文件"
          name="file"
          action="upload.do"
          fieldProps={{
            //限制条件
            // ...Upload,
            // maxCount: 1, // 数量
            accept: '.xlsx',
          }}
        />
        <ProFormText name={'tableName'} hidden />
      </ModalForm>,
    );
  }
  MyExtra.push(
    <Button
      type="primary"
      key="2"
      onClick={() => window.open(TemplateUrlAdapter(tableName))}
    >
      <DownloadOutlined />
      下载模板
    </Button>,
  );

  return MyExtra;
};

/**
 * 详情页面的上传+查看材料 函数
 * @param materialPath 表单中已经填写的材料地址
 * @param setMaterialPath 回填表单材料地址函数
 * @param tableName 表名称--用于显示对应上传文件的格式要求
 * @returns 组件数组
 */
export const MaterialUpload = (
  materialPath: any,
  setMaterialPath: (path: any) => void,
  tableName: string,
) => {
  const MateriaExtra = [];
  /**
   * 坑————只能在常规组件中调用hooks，不能在JavaScript函数中调用hooks
   */
  // const [newPath, setNewpath] = useState(materialPath || '');
  // useEffect(() => {
  //   setNewpath(materialPath);
  // }, []);
  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    accept: '.docx,.doc,.pdf,.xls', //设置上传类型，假限制，全靠用户自觉
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log('uploading...');
      }
      if (info.file.status === 'done') {
        console.log(info?.file?.response?.code == 401);
        console.log(info);

        if (info?.file?.response?.code == 200) {
          //回填材料地址
          setMaterialPath(info?.file?.response.data);
          message.success(`${info.file.name} 上传成功！`);
        } else if (info?.file?.response?.code == 401) {
          message.error('用户登录过期请重新登陆！');
        } else {
          message.error(`${info.file.name} 上传失败`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };
  return (
    <>
      <Button
        type="link"
        onClick={() => {
          // 传递 材料地址
          materialPath ? window.open(materialPath) : message.info('请上传材料');
        }}
        icon={<FileSearchOutlined />}
      >
        查看材料
      </Button>

      <ModalForm
        title="上传材料"
        trigger={
          <Button icon={<UploadOutlined />} type="link">
            上传材料
          </Button>
        }
        autoFocusFirstInput
        submitTimeout={2000}
        onFinish={async (values) => true}
      >
        {/* TbaleExplainMap['STANDARD'] 要修改 */}
        <ProCard title={TbaleExplainMap[`${tableName}`]}>
          {/* 有小问题，需要修改成pro的dragger */}
          <Dragger {...props} maxCount={1}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
            <p className="ant-upload-hint">请上传一个文件</p>
          </Dragger>
        </ProCard>
      </ModalForm>
    </>
  );
};
